<template>
  <el-upload
      ref="uploadRef"
      class="avatar-uploader"
      :action="uploadApi"
      :show-file-list="true"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      title="必须先选择所属公司才能上传"
      :multiple="false"
      v-model:file-list="fileList"
  >
    <el-button type="primary" size="small" @click="beforeUpload">点击上传</el-button>
    <template #tip>
      <div class="el-upload__tip">
      </div>
    </template>
  </el-upload>
</template>

<script lang="ts" setup>
import {ElMessage, type UploadInstance, type UploadUserFile} from 'element-plus'

import type {UploadProps} from 'element-plus'
import {computed, ref, useTemplateRef, watchEffect} from "vue";

const imageUrlInRemote = defineModel({
  type: String,
  default: ''
})

const fileList = ref<UploadUserFile[]>([])

watchEffect(() => {
  if (imageUrlInRemote.value?.length > 0) {
    fileList.value.push({
      name: imageUrlInRemote.value ?? '',
      url: imageUrlInRemote.value
    })
  }
})
const imageUrl = ref()
const companyId = defineModel('companyId', {
  type: Number,
});

const uploader = useTemplateRef<UploadInstance>("uploadRef")


const beforeUpload = (event: any) => {
  if (companyId.value == undefined) {
    ElMessage.error('请先选择所属公司才能上传文件')
    event.stopPropagation()
  }
}


const uploadApi = computed(() => {
  return import.meta.env.VITE_API_BASE_URL + '/file?gs_id=' + companyId.value;
})

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    _response,
    uploadFile
) => {
  imageUrlInRemote.value = _response;
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('Avatar picture size can not exceed 5MB!')
    return false
  }
  return true
}

const clearFiles = () => {
  imageUrlInRemote.value = ''
  uploader.value?.clearFiles()
}

defineExpose({
  clearFiles
})
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>